//
//  UserCenterCtrl.m
//  cutter
//
//  Created by mac on 16/2/19.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "OtherCenter.h"
#import "UITreeView.h"
#import "UserCenterNew.h"
#import "UserCenterCtrl.h"
//
@implementation UserCenterInfo
@end
//
@implementation UserCenterEdit
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.presentationController) {
        UIView *parent = [[self.navigationController view] superview];
        if (parent) {
            [parent.layer setCornerRadius:6];
        }else{
            parent = [self.view superview];
            if (parent) {
                [parent.layer setCornerRadius:6];
            }
        }
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.onSelected) {
        self.onSelected(self, indexPath);
    }
}
@end
//
@implementation UserCenterCell
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];
    if ([self.reuseIdentifier isEqualToString:@"cellIdentifier"]) {
        if (selected) {
            [self setBackgroundColor:[UIColor colorWithHex:0xD2E5FB]];
        }else{
            [self setBackgroundColor:[UIColor colorWithHex:0xF7F7F7]];
        }
        //
        id client = [TMGlobal valueForKey:@"client"];
        if ([client[@"uuid"] isEqual:self.client[@"uuid"]]) {
            [self.clientView setSelected:YES];
            [self.clientView setHidden:NO];
        }else{
            [self.clientView setSelected:NO];
            [self.clientView setHidden:!selected];
        }
    }else{
        if (selected) {
            [UIView beginAnimations:nil context:nil];
            [self setBackgroundColor:[UIColor colorWithHex:0xF7F7F7]];
            [self.arrowView setTransform:CGAffineTransformMakeRotation(M_PI_2)];
            [UIView commitAnimations];
        }else{
            [UIView beginAnimations:nil context:nil];
            [self setBackgroundColor:[UIColor whiteColor]];
            [self.arrowView setTransform:CGAffineTransformIdentity];
            [UIView commitAnimations];
        }
    }
}
@end

@implementation UserCenterCtrl
-(void)viewDidLoad{
    [super viewDidLoad];
    [self.searchView setDelegate:self];
    //
    [self.clientView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.clientView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.clientView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.clientView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    [self headerRefresh:nil];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (isEmpty(textField.text)) {
        [self.condition setValue:nil forKey:@"keyword"];
    }else{
        [self.condition setValue:textField.text forKey:@"keyword"];
    }
    [self headerRefresh:nil];
    return YES;
}
-(NSMutableDictionary *)condition{
    if (nil == _condition) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    return _condition;
}
//
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self initAppear];
}
-(void)initAppear{
    if (self.client == nil) {
        [self setClient:[TMGlobal valueForKey:@"client"]];
        [self setGroupid:[self.client objectForKey:@"groupid"]];
    }
    if ([TMGlobal valueForKey:@"clientTag"]) {
        NSInteger tag = [[TMGlobal valueForKey:@"clientTag"] integerValue];
        [TMGlobal setValue:nil forKey:@"clientTag"];
        //
        UIButton *btn = [self.tabarView viewWithTag:tag + 1];
        if (btn) {
            [btn sendActionsForControlEvents:UIControlEventTouchUpInside];
        }
    }
}
-(void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.clientView.headerView;
        [sender beginRefreshing];
    }
    __weak UserCenterCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UITreeNode *rootNode = nil;
        if ([this.condition objectForKey:@"keyword"]) {
            id clients = [AppData userClient:this.condition user:[TMGlobal valueForKey:@"user"]];
            if (clients) {
                id root = [NSDictionary dictionaryWithObject:clients forKey:@"clients"];
                rootNode = [this makeNodesWithData:root level:0];
            }
        }else{
            NSArray *groups = [AppData userClientGroup:[TMGlobal valueForKey:@"user"]];
            if (groups) {
                for (id group in groups) {
                    id clients = [AppData userClient:group user:nil];
                    if (clients) {
                        [group setValue:clients forKey:@"clients"];
                    }
                }
                id root = [NSDictionary dictionaryWithObject:groups forKey:@"clients"];
                rootNode = [this makeNodesWithData:root level:-1];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [this expandClient:rootNode];
            [this.clientView setRootNode:rootNode];
            [this updataClient];
        });
    });
}

-(UITreeNode*)makeNodesWithData:(id)data level:(NSInteger)level{
    static NSInteger identify = 0;
    UITreeNode *nodes = [[UITreeNode alloc] init];
    nodes.idetify = identify++;
    nodes.level = level;
    nodes.value = data;
    //
    id group = [data objectForKey:@"group"];
    if (group) {
        [data setValue:[group objectForKey:@"groupname"] forKey:@"groupname"];
    }
    //
    id child = [data objectForKey:@"clients"];
    if (child) {
        for (id item in child) {
            [nodes addNode:[self makeNodesWithData:item level:level + 1]];
        }
    }
    return nodes;
}
-(void)expandClient:(UITreeNode*)root{
    for (UITreeNode *group in root.nodes) {
        if (self.client) {
            for (UITreeNode *node in group.nodes) {
                if ([node.value[@"uuid"] isEqual:self.client[@"uuid"]]) {
                    [self setGroupid:group.value[@"uuid"]];
                    [group setExpand:YES];
                    [node setSelect:YES];
                    return;
                }
            }
        }
        if (self.groupid) {
            if ([group.value[@"uuid"] isEqual:self.groupid]) {
                [group setExpand:YES];
                return;
            }
        }
    }
}
-(void)updataClient{
    if (self.client && self.infoCtrl) {
        NSMutableArray *temp = [NSMutableArray array];
        id a = [self.client objectForKey:@"provincename"];
        if (isEmpty(a) == NO) {
            [temp addObject:a];
        }
        id b = [self.client objectForKey:@"cityname"];
        if (isEmpty(b) == NO) {
            [temp addObject:b];
        }
        id c = [self.client objectForKey:@"areaname"];
        if (isEmpty(c) == NO) {
            [temp addObject:c];
        }
        [self setGroupid:[self.client objectForKey:@"groupid"]];
        [self.nameView setText:[AppData objToString:[self.client objectForKey:@"truename"] lable:nil]];
        [self.groupView setText:[AppData objToString:[self.client objectForKey:@"groupname"] lable:nil]];
        [self.infoCtrl.nameView setText:[AppData objToString:[self.client objectForKey:@"truename"] lable:nil]];
        [self.infoCtrl.mobileView setText:[AppData objToString:[self.client objectForKey:@"mobile"] lable:nil]];
        [self.infoCtrl.emailView setText:[AppData objToString:[self.client objectForKey:@"email"] lable:nil]];
        [self.infoCtrl.addressView setText:[AppData objToString:[self.client objectForKey:@"address"] lable:nil]];
        if ([temp count] > 0) {
            [self.infoCtrl.areaView setText:[temp componentsJoinedByString:@"-"]];
        }
        [self.emptyView setHidden:YES];
    }else{
        [self.nameView setText:@""];
        [self.groupView setText:@""];
        [self.infoCtrl.nameView setText:@""];
        [self.infoCtrl.mobileView setText:@""];
        [self.infoCtrl.emailView setText:@""];
        [self.infoCtrl.addressView setText:@""];
        [self.infoCtrl.areaView setText:@""];
        [self.emptyView setHidden:NO];
    }
    //
    BOOL enabled = self.client != nil;
    [self.moreView setEnabled:enabled];
    for (UIButton *btn in self.tabarView.subviews) {
        if ([btn isKindOfClass:UIButton.class]) {
            [btn setEnabled:enabled];
        }
    }
}
-(void)clientTouch:(UIButton*)sender{
    if (sender) {
        UITreeNode *node = [self.clientView nodeAtIndex:sender.tag];
        if (node) {
            [TMGlobal setValue:node.value forKey:@"client"];
            [self updataClient];
            //
            NSArray *cells = [self.clientView visibleCells];
            for (UserCenterCell *cell in cells) {
                [cell.clientView setHidden:YES];
            }
            [sender setSelected:YES];
            [sender setHidden:NO];
        }
    }
}
//UITreeView
-(void)treeView:(UITreeView *)treeView expandRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    for (UITreeNode *item in treeView.visibleNodes) {
        [item setSelect:node == item];
    }
    //
    if (node.level >  0) {
        [self.clientView expand:node];
        [self setClient:node.value];
        [self updataClient];
    }else{
        [self.clientView collapseAll];
        [self.clientView expand:node];
        for (UITreeNode *child in node.nodes) {
            if ([child.value[@"uuid"] isEqual:self.client[@"uuid"]]) {
                [self.clientView expand:child];
                return;
            }
        }
    }
}
-(void)treeView:(UITreeView *)treeView collapseRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node) {
        [node setSelect:NO];
        [self.clientView collapse:node];
    }
}
-(UITableViewCell *)treeView:(UITreeView *)treeView cellForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level == 0) {
        UserCenterCell *cell=[treeView dequeueReusableCellWithIdentifier:@"headIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"groupname"]];
        return cell;
    }
    UserCenterCell *cell=[treeView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    [cell.clientView addTarget:self action:@selector(clientTouch:) forControlEvents:UIControlEventTouchUpInside];
    [cell.nameView setText:[node.value objectForKey:@"truename"]];
    [cell.clientView setTag:index];
    [cell setClient:node.value];
    return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak UserCenterCtrl *this = self;
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *root = segue.destinationViewController;
        //客户
        if ([[root.viewControllers firstObject] isKindOfClass:UserCenterNew.class]) {
            UserCenterNew *temp = [root.viewControllers firstObject];
            [temp setOnSelected:^(id target, id result){
                [this dismissViewControllerAnimated:YES completion:^{
                    if (result) {
                        [TMGlobal setValue:result forKey:@"client"];
                        [this setClient:result];
                        [this headerRefresh:nil];
                    }
                }];
            }];
            [temp setClient:sender ? nil : self.client];
            return;
        }
        //编辑
        if ([[root.viewControllers firstObject] isKindOfClass:UserCenterGroup.class]) {
            UserCenterGroup *temp = [root.viewControllers firstObject];
            [temp setIsEdit:sender != nil];
            [temp setOnSelected:^(id target, id result){
                [this dismissViewControllerAnimated:YES completion:^{
                    if (result) {
                        if (temp.isEdit == NO && this.client) {
                            [this.client setValue:[result objectForKey:@"uuid"] forKey:@"groupid"];
                            [AppData userEditClient:this.client];
                        }
                    }
                    [this headerRefresh:nil];
                    [this updataClient];
                }];
            }];
            return;
        }
    }
    if ([segue.destinationViewController isKindOfClass:OtherCenter.class]) {
        OtherCenter *ctrl = segue.destinationViewController;
        if ([sender isKindOfClass:UIButton.class]) {
            [this setSelectedIndex:[(UIButton*)sender tag] - 1];
            [ctrl setUserCenterCtrl:self];
        }
    }
    if ([segue.destinationViewController isKindOfClass:UserCenterInfo.class]) {
        UserCenterInfo *ctrl = segue.destinationViewController;
        [self setInfoCtrl:ctrl];
        [self updataClient];
    }
    //
    UIPopoverPresentationController *popover = [segue.destinationViewController popoverPresentationController];
    if (popover) {
        UIButton *view = sender;
        [popover setSourceView:view];
        [popover setSourceRect:view.bounds];
        //
        if ([segue.destinationViewController isKindOfClass:UserCenterEdit.class]) {
            UserCenterEdit *ctrl = segue.destinationViewController;
            [ctrl setOnSelected:^(id target, id result){
                [this dismissViewControllerAnimated:NO completion:nil];
                //
                NSIndexPath *indexPath = result;
                switch (indexPath.row) {
                    case 2:
                        [this logoutCliend:nil];
                        break;
                    case 1:
                        [this deleteCliend:nil];
                        break;
                    default:
                        [this editCliend:nil];
                        break;
                }
            }];
        }
    }
}
//
-(void)editCliend:(UIButton *)sender {
    if (self.client) {
        [self performSegueWithIdentifier:@"editSegue" sender:nil];
    }
}
-(void)deleteCliend:(UIButton *)sender {
    if (self.client) {
        __weak UserCenterCtrl *this = self;
        NSString *tit = [NSString stringWithFormat:@"确定要删除“%@”吗?", [self.client objectForKey:@"truename"]];
        NSString *msg = @"删除客户后，他（她）的收藏、购物车、订单将被删除。设计搭配、空间方案、户型沙盘将会保留在设计管理中。";
        UIAlertController *ctrl = [UIAlertController show:tit message:msg buttons:@[@"删除", @"取消"] handler:^(UIAlertAction *action) {
            if ([action.title isEqualToString:@"删除"]) {
                if ([AppData userDeleteClient:this.client]) {
                    id current = [TMGlobal valueForKey:@"client"];
                    if ([[current objectForKey:@"uuid"] isEqualToString:[this.client objectForKey:@"uuid"]]) {
                        [TMGlobal setValue:nil forKey:@"client"];
                    }
                    [this setClient:nil];
                    [this headerRefresh:nil];
                };
            }
        }];
        [self presentViewController:ctrl animated:YES completion:nil];
    }
}
-(void)logoutCliend:(UIButton *)sender {
    __weak UserCenterCtrl *this = self;
    UIAlertController *ctrl = [UIAlertController show:@"确定要注销当前客户吗？" message:@"注销后，在设计搭配等工具进行保存时，文件不会默认保存在该用户下。" buttons:@[@"注销", @"取消"] handler:^(UIAlertAction *action) {
        if ([action.title isEqualToString:@"注销"]) {
            [TMGlobal setValue:nil forKey:@"client"];
            [this headerRefresh:nil];
        }
    }];
    [self presentViewController:ctrl animated:YES completion:nil];
}
-(IBAction)exitTouch:(UIButton *)sender {
    IndexHomeCtrl *tabbar = (id)self.splitViewController;
    if ([tabbar isKindOfClass:IndexHomeCtrl.class]) {
        [tabbar showMenu];
    }
}
@end
